package com.example.test;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 咔咔吃萝卜 on 2017/5/17.
 */

public class SerachActivity extends Activity {
    private ListView listView;
    private Button button;
    private EditText editText;
    private String[] cities = {"北京 朝阳", "江苏 宿迁", "江苏 南京", "江苏 徐州", "辽宁 朝阳"};
    private List<Map<String, Object>> listems = new ArrayList<Map<String, Object>>();
    private String url = "http://api.jisuapi.com/weather/city?appkey=88a8f480061791e6";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_layout);

        listView = (ListView) findViewById(R.id.result_list);
        button = (Button) findViewById(R.id.search_button);
        editText = (EditText) findViewById(R.id.search_text);


        //点击搜索出现对应的地名
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listems.clear();
               String location = editText.getText().toString();
                new MyAsyncTask(location).execute();
            }
        });

        //点击地名跳到第一个页面
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = getIntent();
                Bundle bundle = new Bundle(); //不能直接从Intent里面获取，因为Intent里面不一定有 所以还是new一个吧
                bundle.putString("city", listems.get(position).get("name").toString());
                intent.putExtras(bundle);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

    }

    public class MyAsyncTask extends AsyncTask<String,Void,LocationBean>{
        String mUrl;
        String mLocation;
        String location = null;
        public MyAsyncTask(String location)
        {
            this.mLocation = location;
        }

        @Override
        protected LocationBean doInBackground(String... params) {
            try {
                this.mUrl = url;
                URL murl = new URL(mUrl);
                URLConnection urlConnection = murl.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                StringBuilder stringBuilder = new StringBuilder();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = null;
                while((line=bufferedReader.readLine())!=null)
                {
                    stringBuilder.append(System.getProperty("line.separator"));
                    stringBuilder.append(line);
                }
                String json = stringBuilder.toString();
                return new Gson().fromJson(json, LocationBean.class);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(LocationBean locationBean) {
            //mLocation为用户输入的地址
            //location为异步类中的全局变量，用来存“从头到尾”的地名
            location = mLocation;
            fun(locationBean,mLocation);

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name",location);
            listems.add(map);
            listView.setAdapter(new SimpleAdapter(getApplication(), listems,
                    R.layout.activity_search_listview_item, new String[]{"name"},
                    new int[]{R.id.result_text}));
        }

        //子城市的爸爸
        public mix ParentLocation(LocationBean locationBean, String childlocation)
        {
            String parentLocation = null;
            String parentid1 = null;
            //找到子城市的父亲城市的id
            for (LocationBean.ResultBean resultBean : locationBean.result) {
                if(resultBean.city.equals(childlocation))
                {
                    //四川的id
                    parentid1 = resultBean.parentid;
                }
            }
            //没有这个城市,flag=0
            if(parentid1==null)
            {
                return new mix(0,parentid1);
            }
            //该城市的爸爸id为0，代表这个孩子已经是最大的了，不用再调用函数了
            if (parentid1.equals("0"))
            {
                for (LocationBean.ResultBean resultBean : locationBean.result) {
                    if(resultBean.cityid.equals(parentid1))
                    {
                        parentLocation = resultBean.city;
                    }
                }
                //flag为1代表的是这个城市已经是最大的城市了
                return new mix(1,parentLocation);
            }
            //该城市有爸爸，需要再次调用
            for (LocationBean.ResultBean resultBean : locationBean.result) {
                if(resultBean.cityid.equals(parentid1))
                {
                    parentLocation = resultBean.city;
                }
            }
            return new mix(2,parentLocation);
        }

        //递归，
        public void fun(LocationBean locationBean,String mLocation)
        {
            mix temp = ParentLocation(locationBean,mLocation);
            if(temp.flag==0)
            {
                location = "没有这个城市";
            }
            //这个城市已经是最大的城市了，不做处理
            if(temp.flag==1)
            {

            }
            //代表这个城市还有上级，比如：成都
            if (temp.flag==2)
            {
                StringBuffer sb = new StringBuffer(location);
                String templ = temp.parentLocation+"\b";
                sb.insert(0,templ);
                location = sb.toString();
                fun(locationBean,temp.parentLocation);
            }
        }
    }


    public class mix
    {
        int flag;
        String parentLocation;
        mix(int flag,String parentLocation)
        {
            this.flag = flag;
            this.parentLocation = parentLocation;
        }
    }

}
